/*
 * FXGL - JavaFX Game Library. The MIT License (MIT).
 * Copyright (c) AlmasB (almaslvl@gmail.com).
 * See LICENSE for details.
 */

package com.windea.study.kotlin.fxgl.sample.sandbox

import com.almasb.fxgl.core.math.*
import com.almasb.fxgl.dsl.*
import com.almasb.fxgl.entity.component.*
import com.almasb.fxgl.texture.*
import javafx.geometry.*
import javafx.util.*

/**
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
class AnimationComponent : Component() {
	private var speed = 0
	
	private val texture: AnimatedTexture
	
	private val animIdle: AnimationChannel = AnimationChannel(FXGL.image("newdude.png"), 4, 32, 42, Duration.seconds(1.0), 1, 1)
	
	private val animWalk: AnimationChannel = AnimationChannel(FXGL.image("newdude.png"), Duration.seconds(1.0), listOf(
		0 to FrameData(0, 0, 32, 42),
		1 to FrameData(32, 0, 32, 42),
		2 to FrameData(32 + 32, 0, 32, 42),
		3 to FrameData(32 + 32 + 32, 0, 32, 42)
	))
	
	init {
		texture = AnimatedTexture(animIdle)
		texture.loop()
	}
	
	override fun onAdded() {
		entity.transformComponent.scaleOrigin = Point2D(16.0, 21.0)
		entity.viewComponent.addChild(texture)
	}
	
	override fun onUpdate(tpf: Double) {
		entity.translateX(speed * tpf)
		
		if(speed != 0) {
			
			if(texture.animationChannel == animIdle) {
				texture.loopAnimationChannel(animWalk)
			}
			
			speed = (speed * 0.9).toInt()
			
			if(FXGLMath.abs(speed.toFloat()) < 1) {
				speed = 0
				texture.loopAnimationChannel(animIdle)
			}
		}
	}
	
	fun moveRight() {
		speed = 150
		
		getEntity().scaleX = 1.0
	}
	
	fun moveLeft() {
		speed = -150
		
		getEntity().scaleX = -1.0
	}
}
